<template>
  <div>
<!--    面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片及表格-->
    <el-card >
      <el-button type="primary" round>添加角色</el-button>
<!--      角色表格页面-->
      <el-table
        :data="rolesList"
        style="width: 100%">
        <!--          子菜单的渲染-->
        <el-table-column type="expand">
          <template v-slot:default="{row}">
            <el-row v-for="(item1,i1) in row.children" :key="item1.id"  :class="['bdbuttom',i1===0 ? 'bdtop':'','vcenter']">
<!--              渲染一级全限-->
              <el-col :span="5" >
                <el-tag @close="removeRightById(row,i2)" closable>
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>

              </el-col>
<!--              渲染二级全限-->
              <el-col :span="19">
                <!--              通过for训话嵌套二级全新啊-->
                <el-row  :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id" >
<!--                                    二级全限渲染-->
                  <el-col :span="6">
                    <el-tag @close="removeRightById(row,item2.id)" closable type="success">{{item2.authName}} </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col >
<!--                  三级全限-->
                  <el-col :span="18">
                        <el-tag closable type="warning" v-for="(item3,i3) in item2.children"
                                :key="i3" :class="[i3==0?'':'bdtop']" @close="removeRightById(row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>

            </el-row>

          </template>
        </el-table-column>
<!--        索引列-->
          <el-table-column
            label="#"
            type="index"
            prop="id">
          </el-table-column>
          <el-table-column
            label="角色名称"
            prop="roleName">
          </el-table-column>
          <el-table-column
            label="角色描述"
            prop="roleDesc">
          </el-table-column>
          <el-table-column label="操作" prop="desc" width="500px">
            <template v-slot:default={row}>
              <el-button icon="el-icon-edit" type="primary" @click="showEditDialog(row.id)">编辑</el-button>
              <el-button icon="el-icon-delete" type="success">删除</el-button>
              <el-button icon="el-icon-setting"  type="info" @click="showSetRightDialog(row)">分配权限</el-button>
            </template>
        </el-table-column>
      </el-table>
    </el-card>
<!--    角色列表编辑-->
    <el-dialog
      title="编辑角色"
      :visible.sync="dialogVisible"
      width="30%">
<!--      编辑角色表单-->
        <el-form  :model="rolesForm" label-width="70px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
<!--   权限分配对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showSetRightDialogVisible"
      width="30%"
      @close="closeRightDialog"
    >
      <!--  :visible.sync="showSetRightDialogVisible"    绑定显示或者消失-->
<!--      树形空间-->
      <el-tree :data="rightsList" :props="treeProps"   show-checkbox node-key="id"
               default-expand-all :default-checked-keys	="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showSetRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
export default {
  data(){
    return{
      rolesList:[],
      dialogVisible: false,
      rolesForm:{
        roleDesc:'',
        roleName:''
      },
      //控制分配权限对话款的显示与隐藏
      showSetRightDialogVisible:false,
      //所有权限的数据
      rightsList:[],
      //树形控件的属性绑定对象
      treeProps:{
        label:'authName',
        children:'children'
      },
      //默认选中的节点的id
      defKeys:[],
      //当前即将分配权限的角色id
      roleId:''

    }
  },
  created() {
    this.getrolesList();
  },
  methods:{
    async getrolesList(){
      const {data:res}=await this.$http.get('/roles');
      if (res.meta.status!==200) return this.$message.error('获取角色列表失败')
      this.rolesList=res.data;
    },
    async removeRightById(role,rightId){
      //弹框提示用户是否要删除

        const confirmResult=
          await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
        if (confirmResult !=='confirm'){
          return this.$message.error('取消了删除')
        }
        const {data:res}=await this.$http.delete('roles/'+role.id+'/rights/' +rightId);
        if (res.meta.status!==200){
          return this.$message.error('删除失败')
        }
         role.children =res.data;
        return this.$message.success('删除成功')
    },
    async showEditDialog(id){
      const {data:res}=await this.$http.get('roles/'+id);
      if (res.meta.status!==200){
        this.$message.error('编辑用户失败')
      }
      this.dialogVisible=true;
      this.rolesForm=res.data.role

    },
    //展示分配权限的对话框
    async showSetRightDialog(role){
      this.roleId=role.id;
      const {data:res}=await this.$http.get('rights/tree');
      if (res.meta.status!==200){
        return this.$message.error('获取权限列表失败')
      }
      //把获取到的权限数据保存到data中
      this.rightsList=res.data;
      console.log(this.rightsList)
      //递归获取三级节点的id
      this.getLeafKeys(role,this.defKeys)
      this.showSetRightDialogVisible=true;
    },
    //通过递归的形式过去角色下所有三级权限的id，保存到defKeys数组中
    getLeafKeys(node,arr){
      //如果当前node节点不包含childre属性，则是三级节点
      if (!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item =>this.getLeafKeys(item,arr))
    },
    //监听对话框关闭事件
    closeRightDialog(){
      this.defKeys=[]
    },
    async allotRights(){
      const keys =[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // join() 方法用于把数组中的所有元素放入一个字符串

      const  idStr=keys.join(',');
      const {data:res}=await this.$http.post('roles/'+this.roleId+'/rights',{rids:idStr})
      if (res.meta.status!==200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功！')
      this.getrolesList()
      this.showSetRightDialogVisible=false;
      console.log(keys)
    }

  }
}
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbuttom {
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display:flex;
    align-items:center;
  }


</style>
